package view;

import java.io.*;
import controller.Controller;


/**
 * A simple example of a command line interface implemented as a view.
 * 
 */
public class CommandLineView implements IView {
	private Controller controller;
	private String input = "";

	/**
	 * Constructor of CommandLineView
	 * @param c	controller
	 */
	public CommandLineView(Controller c) {
		setController(c);
		c.setView(this);
		System.out.println("A very cool (text-based) search engine!");
		System.out.println(c.toString());
		System.out.println("To exit, press enter.");

		//get search query
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		while (true) {
			System.out.println("Enter search term: ");
			try {
				input = br.readLine().trim();
			} catch (IOException ioe) {
				System.out.println("IO error!");
				System.exit(1);
			}
			if (input.equals(""))
				System.exit(1);
			doSearch();
		}
	}

	@Override
	public void doSearch() {
		controller.doSearch(input);
	}

	@Override
	public void setController(Controller ctrl) {
		controller = ctrl;
	}

	@Override
	public void showResult(String[] result) {
		if (result == null || result.length == 0) {
			System.out.print("No match found: " + input + "\n");
		} else if (result[0].startsWith("null")) {
			System.out.print("No match found: " + input + "\n");
		} else {
			System.out.print("\nResults for search: " + input + "\n");
			for (String s : result) {
				System.out.print(s + "\n");
			}
			System.out.println(result.length + " results in total.");
		}
	}

	
	@Override
	public String toString() {
		return this.getClass().getName();
	}
}
